import React,{useEffect, useState,useRef} from 'react'
import {getRightList} from '../services/index'
import {RightItem} from '../untils/interface'
import  styles from './message.module.scss'
import BScroll from '@better-scroll/core'
import Pulldown from '@better-scroll/pull-down'
import { BScrollConstructor } from '@better-scroll/core/dist/types/BScroll';
import {PluginAPI} from '@better-scroll/pull-down/dist/types'
BScroll.use(Pulldown)
let scroll:BScrollConstructor&PluginAPI
const Message:React.FC=()=>{
    let [list,setList]=useState<RightItem[]>([])
    let [page,setPage]=useState(1)
    let [hasMore,setHasMore]=useState(true)
    //ref绑定元素
    let ele=useRef(null)
    //开关
    let flag=false
    //下拉加载
    useEffect(()=>{
        scroll=new BScroll("#wrap",{
            pullDownRefresh:true
        })
        scroll.on('pullingDown',()=>{
            console.log(555)
            getRightList(page)
            setPage(1)
        })
    },[])
    //渲染
    useEffect(()=>{
        getlist()
    },[page])
    //封装函数
    async function getlist() {
        if(flag){
            return
        }
        flag = true;
        let res=await getRightList(page)
        flag = false;
        scroll.finishPullDown();
        setHasMore(res.data.pageNo < res.data.totalPage)
        if(page===1){
            setList(res.data.dataList)
        }else{
            setList([...list,...res.data.dataList])
        }
    }

    //上拉刷新
    function scrollEvent(e: React.UIEvent<HTMLDivElement>){
        if (!hasMore || flag){
            return;
        }
        let wrap = e.currentTarget;
        if (wrap.clientHeight + wrap.scrollTop > (ele.current as any).clientHeight - 10){
            setPage(page+1);
        }
    }
    return <div className={styles.wrap} id='wrap' onScroll={scrollEvent}>
        <ul ref={ele}>
        {
                list.map((item,index)=>{
                    return <li key={index}>
                        <img src="" alt="" className={styles.icon}/>
                        <p className={styles.con}>
                        <span>{item.title}</span>
                        <span>{item.sendDate}</span>
                        </p>
                     
                    </li>
                })
            }
        </ul>
           
    </div>
}
export default Message